package main

import (
	"context"
	"fmt"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"

	//"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/tools/clientcmd"
)

/*
*
@Author: cloudea
@Desc:  获取kube-system下的pod列表
*/
func main() {
	/** 1. 加载配置文件，生成配置对象 */
	config, err := clientcmd.BuildConfigFromFlags("", "/home/cloudea/.kube/config")
	if err != nil {
		panic(err.Error())
	}

	/** 实例化client set*/
	dynamicClient, err := dynamic.NewForConfig(config)

	if err != nil {
		panic(err.Error())
	}

	/**
	请求过程：
		Resource() 生成了一个针对资源的客户端： DynamicClient -> DynamicResourceClient
		Namespace() 返回一个ResourceInterface 对象，持有RestClient和namespace
		List() 调用客户端并返回二进制的json数据，然后解析成UnStructedList
	*/
	gvr := schema.GroupVersionResource{
		Group:    "", // "即core 资源组"
		Version:  "v1",
		Resource: "pods",
	}
	unstructedData, err := dynamicClient.Resource(gvr).Namespace("kube-system").List(context.TODO(), metav1.ListOptions{})

	// .Apply
	// .Status
	// .Create
	// .Get
	// .List
	// .Patch
	// .Update
	// .UpdateStatus
	// .Watch
	// .Delete
	// .DeleteCollection

	if err != nil {
		panic(err.Error())
	}

	// 把非结构转成结构化数据
	pods := &corev1.PodList{}
	err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstructedData.UnstructuredContent(), pods)
	if err != nil {
		panic(err.Error())
	}

	for _, item := range pods.Items {
		fmt.Println(item.Name)
	}
}
